package com.yiwenup.leetcode.hot;

/**
 * @PROJECT struct-algorithm
 * @PACKAGE com.yiwenup.leetcode.hot
 * @Author yiwenup
 * @Date 2022-03-09 22:06:00
 * <p>
 * @DESCRIPTION https://leetcode-cn.com/problems/implement-trie-prefix-tree/
 *
 * <pre>
 *     执行用时：31 ms, 在所有 Java 提交中击败了96.20%的用户
 *     内存消耗：50.5 MB, 在所有 Java 提交中击败了17.29%的用户
 * </pre>
 */
public class No0208 {

    static class TrieNode {
        boolean isEnd;
        TrieNode[] children;

        public TrieNode() {
            isEnd = false;
            children = new TrieNode[26];
        }
    }

    private TrieNode root;

    public No0208() {
        root = new TrieNode();
    }

    public void insert(String word) {
        TrieNode node = this.root;
        for (char c : word.toCharArray()) {
            if (node.children[c - 'a'] == null) {
                node.children[c - 'a'] = new TrieNode();
            }
            node = node.children[c - 'a'];
        }
        node.isEnd = true;
    }

    public boolean search(String word) {
        TrieNode node = this.root;
        for (char c : word.toCharArray()) {
            node = node.children[c - 'a'];
            if (node == null) return false;
        }
        return node.isEnd;
    }

    public boolean startsWith(String prefix) {
        TrieNode node = this.root;
        for (char c : prefix.toCharArray()) {
            node = node.children[c - 'a'];
            if (node == null) return false;
        }
        return true;
    }
}
